package com.haixiaoke.saas.houseMember.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.haixiaoke.saas.common.constant.HouseMemberConstants;
import com.haixiaoke.saas.common.constant.LockConstants;
import com.haixiaoke.saas.common.exception.ServiceException;
import com.haixiaoke.saas.common.utils.DateUtils;
import com.haixiaoke.saas.common.utils.DesensitizeUtils;
import com.haixiaoke.saas.house.domain.House;
import com.haixiaoke.saas.house.service.IHouseService;
import com.haixiaoke.saas.houseMember.domain.HouseMember;
import com.haixiaoke.saas.houseMember.mapper.HouseMemberMapper;
import com.haixiaoke.saas.houseMember.service.IHouseMemberService;
import com.haixiaoke.saas.lock.domain.HouseLock;
import com.haixiaoke.saas.lock.domain.LockFace;
import com.haixiaoke.saas.lock.service.IHouseLockService;
import com.haixiaoke.saas.lock.service.ILockFaceService;
import com.haixiaoke.saas.lock.service.LockDevicesService;
import com.haixiaoke.saas.order.domain.OrderLessee;
import com.haixiaoke.saas.user.domain.UserConsumer;
import com.haixiaoke.saas.user.service.IUserConsumerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 房屋成员Service业务层处理
 *
 * @author qixi
 * @date 2024-03-07
 */
@Service
public class HouseMemberServiceImpl implements IHouseMemberService {
    @Autowired
    private HouseMemberMapper houseMemberMapper;
    @Autowired
    private IHouseService houseService;
    @Autowired
    private IHouseLockService houseLockService;
    @Autowired
    private ILockFaceService lockFaceService;
    @Autowired
    private LockDevicesService lockDevicesService;
    @Autowired
    private IUserConsumerService userConsumerService;

    /**
     * 查询房屋成员
     *
     * @param memberId 房屋成员主键
     * @return 房屋成员
     */
    @Override
    public HouseMember selectHouseMemberByMemberId(Long memberId) {
        HouseMember houseMember = houseMemberMapper.selectHouseMemberByMemberId(memberId);
        String idCardImgs = houseMember.getIdCardImgs();
        if (StrUtil.isNotBlank(idCardImgs)) {
            List<String> stringList = StrUtil.split(idCardImgs, ',');
            houseMember.setIdCardImgsList(stringList);
        }
        return houseMember;
    }

    /**
     * 查询房屋成员列表
     *
     * @param houseMember 房屋成员
     * @return 房屋成员
     */
    @Override
    public List<HouseMember> selectHouseMemberList(HouseMember houseMember) {
        List<HouseMember> houseMembers = houseMemberMapper.selectHouseMemberList(houseMember);
        houseMembers.forEach(x -> {
            String idCardImgs = x.getIdCardImgs();
            if (StrUtil.isNotBlank(idCardImgs)) {
                List<String> stringList = StrUtil.split(idCardImgs, ',');
                x.setIdCardImgsList(stringList);
            }
        });

        return houseMembers;
    }

    /**
     * 新增房屋成员
     *
     * @param houseMember 房屋成员
     * @return 结果
     */
    @Override
    public int insertHouseMember(HouseMember houseMember) {
        List<String> idCardImgsList = houseMember.getIdCardImgsList();
        if (CollectionUtil.isNotEmpty(idCardImgsList)) {
            String join = CollectionUtil.join(idCardImgsList, ",");
            houseMember.setIdCardImgs(join);
        }
        String orderId = houseMember.getOrderId();

        if (StrUtil.isNotBlank(houseMember.getIdCard())) {
            int genderByIdCard = IdcardUtil.getGenderByIdCard(houseMember.getIdCard());
            houseMember.setSex(genderByIdCard == 1 ? OrderLessee.LESSEE_SEX_MAN : OrderLessee.LESSEE_SEX_WOMAN);
        }


        String memberPhone = houseMember.getMemberPhone();
        if (StrUtil.isNotEmpty(memberPhone)) {
            UserConsumer userConsumer = userConsumerService.selectUserConsumerByMobile(memberPhone);
            if (ObjectUtil.isEmpty(userConsumer)) {
                UserConsumer newConsumer = new UserConsumer();
                newConsumer.setUserMobile(memberPhone);
                newConsumer.setCreateTime(DateUtils.getNowDate());
                newConsumer.setUserName(houseMember.getMemberName());
                userConsumerService.insertUserConsumer(newConsumer);
                userConsumer = newConsumer;
            }
            houseMember.setUserId(userConsumer.getUserId());
        }


        // 判断承租人和房管员是否已存在
        String memberType = houseMember.getMemberType();
        if (StrUtil.equals(memberType, HouseMember.MEMBER_TYPE_TENANTRY) || StrUtil.equals(memberType, HouseMember.MEMBER_TYPE_ROOM_MANAGER)) {
            List<HouseMember> houseMembers = this.selectHouseMemberListByOrderId(orderId);
            List<HouseMember> houseMemberList = houseMembers.stream().filter(x -> StrUtil.equals(x.getMemberType(), memberType)).collect(Collectors.toList());
            if (houseMemberList.size() > 0) {
                if (StrUtil.equals(memberType, HouseMember.MEMBER_TYPE_TENANTRY)) {
                    throw new ServiceException("承租人已存在");
                } else {
                    throw new ServiceException("房管员已存在");
                }
            }
        }
        houseMember.setCreateTime(DateUtils.getNowDate());

        return houseMemberMapper.insertHouseMember(houseMember);
    }

    /**
     * 修改房屋成员
     *
     * @param houseMember 房屋成员
     * @return 结果
     */
    @Override
    public int updateHouseMember(HouseMember houseMember) {
        HouseMember houseMemberByMemberId = selectHouseMemberByMemberId(houseMember.getMemberId());
        if (ObjectUtil.isNull(houseMemberByMemberId)) {
            throw new ServiceException("成员不存在");
        }

        if (StrUtil.isNotBlank(houseMember.getIdCard())) {
            int genderByIdCard = IdcardUtil.getGenderByIdCard(houseMember.getIdCard());
            houseMember.setSex(genderByIdCard == 1 ? OrderLessee.LESSEE_SEX_MAN : OrderLessee.LESSEE_SEX_WOMAN);
        }

        List<String> idCardImgsList = houseMember.getIdCardImgsList();
        if (CollectionUtil.isNotEmpty(idCardImgsList)) {
            String join = CollectionUtil.join(idCardImgsList, ",");
            houseMember.setIdCardImgs(join);
        }

        String memberType = houseMemberByMemberId.getMemberType();
        if (StrUtil.equals(memberType, HouseMember.MEMBER_TYPE_TENANTRY) || StrUtil.equals(memberType, HouseMember.MEMBER_TYPE_ROOM_MANAGER)) {
            throw new ServiceException("承租人和房管员信息不能修改");
        }

        String memberPhone = houseMember.getMemberPhone();
        if (StrUtil.isNotEmpty(memberPhone)) {
            UserConsumer userConsumer = userConsumerService.selectUserConsumerByMobile(memberPhone);
            if (ObjectUtil.isEmpty(userConsumer)) {
                UserConsumer newConsumer = new UserConsumer();
                newConsumer.setUserMobile(memberPhone);
                newConsumer.setCreateTime(DateUtils.getNowDate());
                newConsumer.setUserName(houseMember.getMemberName());
                userConsumerService.insertUserConsumer(newConsumer);
                userConsumer = newConsumer;
            }
            houseMember.setUserId(userConsumer.getUserId());
        }

        houseMember.setUpdateTime(DateUtils.getNowDate());
        return houseMemberMapper.updateHouseMember(houseMember);
    }

    /**
     * 批量删除房屋成员
     *
     * @param memberIds 需要删除的房屋成员主键
     * @return 结果
     */
    @Override
    public int deleteHouseMemberByMemberIds(Long[] memberIds) {
        List<HouseMember> houseMembers = this.selectHouseMemberByMemberIds(memberIds);
        for (HouseMember houseMember : houseMembers) {
            String memberType = houseMember.getMemberType();
            if (StrUtil.equals(memberType, HouseMember.MEMBER_TYPE_TENANTRY)) {
                throw new ServiceException("承租人不能删除");
            }
        }
        return houseMemberMapper.deleteHouseMemberByMemberIds(memberIds);
    }

    /**
     * 删除房屋成员信息
     *
     * @param memberId 房屋成员主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteHouseMemberByMemberId(Long memberId) {
        HouseMember houseMember = selectHouseMemberByMemberId(memberId);
        if (ObjectUtil.isNull(houseMember)) {
            throw new ServiceException("成员不存在");
        }
        String memberType = houseMember.getMemberType();
        if (StrUtil.equals(memberType, HouseMember.MEMBER_TYPE_TENANTRY) || StrUtil.equals(memberType, HouseMember.MEMBER_TYPE_ROOM_MANAGER)) {
            throw new ServiceException("承租人或房管员不能删除");
        }

        // 删除租客人脸信息
        if (HouseMemberConstants.AUTH_STATE_YES.equals(houseMember.getAuthState())) {
            Long[] faceIds = lockFaceService.selectLockFaceListAndLockState(houseMember.getHouseId(), houseMember.getUserId(), HouseLock.LOCK_STATE_NORMAL);
            if (faceIds != null && faceIds.length != 0) {
                for (Long id : faceIds) {
                    houseLockService.removeLockFace(id);
                }
            }

            Long[] ids = lockFaceService.selectLockFaceListAndLockState(houseMember.getHouseId(), houseMember.getUserId(), HouseLock.LOCK_STATE_FROZEN);
            if (ids != null && ids.length != 0) {
                houseLockService.deleteHouseLockByLockIds(ids);
            }
        }

        return houseMemberMapper.deleteHouseMemberByMemberId(memberId);
    }

    @Override
    public int countMemberNumberByOrderId(String orderId) {
        return houseMemberMapper.countMemberNumberByOrderId(orderId);
    }

    @Override
    public List<HouseMember> selectHouseMemberListByOrderId(String orderId) {
        List<HouseMember> houseMembers = houseMemberMapper.selectHouseMemberListByOrderId(orderId);
        houseMembers.forEach(x -> {
            String idCardImgs = x.getIdCardImgs();
            if (StrUtil.isNotBlank(idCardImgs)) {
                List<String> stringList = StrUtil.split(idCardImgs, ',');
                x.setIdCardImgsList(stringList);
            }
        });
        return houseMembers;
    }

    @Override
    public List<HouseMember> selectHouseMemberByMemberIds(Long[] memberIds) {
        return houseMemberMapper.selectHouseMemberByMemberIds(memberIds);
    }

    @Override
    public int rentingTerminationByOrderId(String orderId) {
        return houseMemberMapper.rentingTerminationByOrderId(orderId);
    }

    @Override
    public int insertBatchHouseMember(List<HouseMember> houseMemberList) {
        return houseMemberMapper.insertBatchHouseMember(houseMemberList);
    }

    @Override
    public HouseMember selectHouseMemberListByMemberPhone(String memberPhone, String orderId) {
        return houseMemberMapper.selectHouseMemberListByMemberPhone(memberPhone, orderId);
    }

    @Override
    public int updateHouseIdByOrderId(String orderId, String houseId) {
        return houseMemberMapper.updateHouseIdByOrderId(orderId, houseId);
    }


    /**
     * 获取用户入住房屋信息
     */
    @Override
    public List<HouseMember> getHouseList(HouseMember houseMember) {
        List<HouseMember> houseMembers = houseMemberMapper.selectHouseMemberListAndOrderId(houseMember);
        houseMembers.forEach(x -> {
            String idCardImgs = x.getIdCardImgs();
            if (StrUtil.isNotBlank(idCardImgs)) {
                List<String> stringList = StrUtil.split(idCardImgs, ',');
                x.setIdCardImgsList(stringList);
            }
        });
        return houseMembers;
    }


    /**
     * 获取入住人信息
     */
    @Override
    public HouseMember getMemberInfo(String orderId, Long userId) {
        HouseMember houseMember = new HouseMember();
        houseMember.setOrderId(orderId);
        List<HouseMember> houseMemberList = houseMemberMapper.selectHouseMemberList(houseMember);
        if (CollectionUtil.isNotEmpty(houseMemberList)) {
            for (HouseMember member : houseMemberList) {
                if (StrUtil.isNotEmpty(member.getMemberPhone())) {
                    member.setMemberPhone(DesensitizeUtils.desensitizePhone(member.getMemberPhone()));
                }
                if (StrUtil.isNotEmpty(member.getIdCard())) {
                    member.setIdCard(DesensitizeUtils.desensitizeIdCard(member.getIdCard()));
                }
            }
        }
        houseMember.setHouseMemberList(houseMemberList);

        HouseMember sqlHouseMember = houseMemberMapper.selectHouseMemberByUserIdAndOrderId(userId, orderId);
        if (ObjectUtil.isNotNull(sqlHouseMember)) {
            houseMember.setLesseeStatus(HouseMemberConstants.LESSEE_STATUS_YES);
        } else {
            houseMember.setLesseeStatus(HouseMemberConstants.LESSEE_STATUS_NO);
        }

        Integer residenceStatusNumber = houseMemberMapper.countMemberNumberByOrderId(orderId);
        House house = houseService.selectHouseById(houseMemberList.get(0).getHouseId());
        if (ObjectUtil.isNotEmpty(house)) {
            if (residenceStatusNumber < house.getCheckInNumber()) {
                houseMember.setCheckInStatus(HouseMemberConstants.CHECKIN_STATUS_YES);
            } else {
                houseMember.setCheckInStatus(HouseMemberConstants.CHECKIN_STATUS_NO);
            }
        }
        return houseMember;
    }

    @Override
    public HouseMember selectHouseMemberListByIdCard(String idCard, String orderId) {
        return houseMemberMapper.selectHouseMemberListByIdCard(idCard, orderId);
    }

    @Override
    @Transactional
    public int authentication(HouseMember houseMember) {
        List<HouseLock> houseLockList = houseLockService.selectHouseLockByHouseIdAndLockState(houseMember.getHouseId(), HouseLock.LOCK_STATE_NORMAL);
        if (CollectionUtil.isNotEmpty(houseLockList)) {
            List<LockFace> lockFaceList = new ArrayList<>();
            for (HouseLock houseLock : houseLockList) {
                String format = DateUtil.format(DateUtil.date(), "yyyyMMdd");
                String identification = format + RandomUtil.randomNumbers(8);

                LockFace lockFace = new LockFace();
                lockFace.setImg(houseMember.getFacePhoto());
                lockFace.setUserType(LockConstants.USER_TYPE_TENANT);
                lockFace.setLockId(houseLock.getLockId());
                lockFace.setUserId(houseMember.getUserId());
                lockFace.setOrderId(houseMember.getOrderId());
                lockFace.setUserName(houseMember.getMemberName());
                lockFace.setCreateBy(houseMember.getUpdateBy());
                lockFace.setHouseId(houseLock.getHouseId());
                lockFace.setIdentification(identification);
                lockFace.setCreateTime(DateUtils.getNowDate());
                lockFaceList.add(lockFace);
                lockDevicesService.createLockFace(lockFace.getImg(), houseLock.getMac(), identification);

            }
            lockFaceService.insertBatchLockFace(lockFaceList);
        }
        houseMember.setUpdateTime(DateUtils.getNowDate());
        houseMember.setAuthState(HouseMemberConstants.AUTH_STATE_YES);
        return houseMemberMapper.updateHouseMember(houseMember);
    }

    @Override
    public int editManager(HouseMember houseMember) {
        HouseMember houseMemberByMemberId = selectHouseMemberByMemberId(houseMember.getMemberId());
        if (ObjectUtil.isNull(houseMemberByMemberId)) {
            throw new ServiceException("成员不存在");
        }
        if (HouseMemberConstants.RESIDENCE_STATUS_YES.equals(houseMember.getResidenceStatus())) {
            House house = houseService.selectHouseById(houseMemberByMemberId.getHouseId());
            if (ObjectUtil.isEmpty(house)) {
                throw new ServiceException("房屋不存在");
            }
            if (houseMemberMapper.countMemberNumberByOrderId(houseMemberByMemberId.getOrderId()) >= house.getCheckInNumber()) {
                throw new ServiceException("房间已达到入住人数上限");
            }
        }
        houseMember.setUpdateTime(DateUtils.getNowDate());
        return houseMemberMapper.updateHouseMember(houseMember);
    }

    @Override
    public List<HouseMember> selectHouseMemberListByHouseId(String houseId) {
        return houseMemberMapper.selectHouseMemberListByHouseId(houseId);
    }

    @Override
    public int updateBatchHouseMember(List<HouseMember> houseMemberList) {
        return houseMemberMapper.updateBatchHouseMember(houseMemberList);
    }

    @Override
    public int deleteHouseMemberByOrderId(String orderId) {
        return houseMemberMapper.deleteHouseMemberByOrderId(orderId);
    }

    @Override
    public int deleteHouseMemberByOrderIds(List<String> orderIds) {
        return houseMemberMapper.deleteHouseMemberByOrderIds(orderIds);
    }

    @Override
    public HouseMember selectHouseMemberByHouseIdAndUserId(String houseId, Long userId) {
        return houseMemberMapper.selectHouseMemberByHouseIdAndUserId(houseId, userId);
    }


}
